var version = '4.1.3'

function getRequest(interfaceStr, params, success) {
  var app = getApp()
  if (app.globalData.token) {
    // console.log(getApp().globalData.shop_id)
    params["shop_id"] = getApp().globalData.shop_id
    console.log(params)
    getRequestWithToken(interfaceStr, params, success)
  } else {
    login({
      success: function(res) {
        console.log("开始登录")
        params["shop_id"] = getApp().globalData.shop_id
        getRequestWithToken(interfaceStr, params, success)
      },
      fail: function(res) {
        wx.showToast({
          title: 'token获取失败',
        })
      }
    })
  }
}

function postRequest(interfaceStr, params, success) {
  var app = getApp()
  if (app.globalData.token) {
    params["shop_id"] = getApp().globalData.shop_id
    postRequestWithToken(interfaceStr, params, success)
  } else {
    login({
      success: function(res) {
        params["shop_id"] = getApp().globalData.shop_id
        postRequestWithToken(interfaceStr, params, success)
      },
      fail: function(res) {
        console.log(res)
        wx.showToast({
          title: 'token获取失败',
        })
      }
    })
  }
}

function getRequestWithToken(interfaceStr, params, success) {
  console.log(params)
  wx.showLoading({
    title: '加载中，请稍后',
  })
  var app = getApp()
  wx.request({
    method: 'GET',
    url: 'https://wx.extend.xuemei99.com/' + interfaceStr,
    // url: 'http://www.show.com/' + interfaceStr,
    data: params,
    header: {
      'Content-type': 'application/json; charset=UTF-8',
      'Authorization': app.globalData.token,
      'version': version,
    },
    success: function(res) {
      console.log(res)
      wx.hideLoading()
      setTimeout(function() {
        wx.stopPullDownRefresh()

      }, 100)
      console.log(interfaceStr + ' 请求成功')
      if (res.data.status == 0) {
        console.log(res.data)
        success(res.data)
      } else {
        console.log(res)
        wx.showModal({
          title: '提示',
          content: res.data.detail,
        })
      }

    },
    fail: function(res) {
      console.log(interfaceStr + ' 请求失败')
      console.log(res)
      setTimeout(function() {
        wx.stopPullDownRefresh()

      }, 100)
    }
  })
}

function login(obj) {
  console.log(obj)
  wx.showLoading({
    title: '请求中，请稍待',
  })
  wx.login({
    success: res => {
      console.log(res)
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      if (res.code) {
        getApp().globalData.code = res.code
        var params = {}
        params['code'] = res.code
        console.log('code' + res.code)
        params['appid'] = getApp().globalData.appid
        wx.request({
          url: 'https://wx.extend.xuemei99.com/xcx/login',
          method: "POST",
          data: params,
          success: function(logRes) {
            console.log('登录成功')
            console.log(logRes)
            var status = logRes.data.status
            if (status == 0) {
              //走已注册
              console.log("已注册" + (logRes.data.detail.owner ? "店主身份" : "游客身份"))
              rerigtered(obj, logRes)
            } else if (status == 2) {
              //走未注册
              unregistered(obj, logRes)
            }
          }
        })
      } else {
        console.log('登录失败' + res.errMsg)
      }
    },
    fail: res => {
      console.log('登录失败')
      console.log(res)
    },
    complete: res => {
      console.log('登录接口调用完毕')
      wx.hideLoading()
    }
  })
}

function postRequestWithToken(interfaceStr, params, success) {
  wx.showLoading({
    title: '加载中，请稍后',
  })
  console.log(params)
  var app = getApp()
  wx.request({
    method: 'POST',
    url: 'https://wx.extend.xuemei99.com/' + interfaceStr,
    // url: 'http://www.show.com/' + interfaceStr,
    data: params,
    header: {
      'Content-type': 'application/json; charset=UTF-8',
      'Authorization': app.globalData.token,
      'version': version
    },
    success: function(res) {
      console.log(res.data)
      console.log(interfaceStr + ' 请求成功')
      setTimeout(function() {
        wx.stopPullDownRefresh()
      }, 100)
      wx.hideLoading()
      if (res.data.status == 0) {
        console.log("成功")
        success(res.data)
      } else {
        console.log("失败")
        wx.showModal({
          title: '提示',
          content: res.data.detail,
        })
      }
    },
    fail: function(res) {
      console.log(interfaceStr + ' 请求失败')
      setTimeout(function() {
        wx.stopPullDownRefresh()
      }, 100)
      console.log(res)
    }
  })
}

function defaultParams() {
  var app = getApp()
  var params = {}
  params['openid'] = app.globalData.openid
  params['appid'] = app.globalData.appid
  return params
}

function shopParams() {
  var app = getApp()
  return {
    shop_id: app.globalData.shop_id
  }
}




function getAuthorization(successCallBack, failCallBack) {
  wx.getUserInfo({
    lang: 'zh_CN',
    success: res => {
      // 可以将 res 发送给后台解码出 unionId
      console.log(res)
      successCallBack(res)
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      // if (this.userInfoReadyCallback) {
      //   this.userInfoReadyCallback(res)
      // }

    },
    fail: res => {
      failCallBack(res)
    }
  })
}

function updateUserinfo(openid, iv, encryptedData, nick, gender, logo, success) {
  var params = defaultParams()
  params['openid'] = openid
  params['nick'] = nick
  params['sex'] = gender
  params['logo'] = logo
  params['iv'] = iv
  params['encrypted_data'] = encryptedData
  console.log(params)
  wx.showLoading({
    title: '加载中，请稍后'
  })
  console.log('注册')
  wx.request({
    method: 'POST',
    url: 'https://wx.extend.xuemei99.com/xcx/register',
    data: params,
    header: {
      'Content-type': 'application/json; charset=UTF-8',
      'version': version
    },
    success: function(res) {
      console.log(res)
      console.log('注册成功' + res)
      wx.hideLoading()
      if (res.data.status == 0) {
        success(res.data)
      } else {
        wx.showToast({
          title: res.data.detail,
          image: '/images/close.png',
        })
      }

    },
    fail: function(res) {
      wx.hideLoading()
      console.log(res)
      console.log(' 请求失败')
    }
  })
}

function getUserInformation(success) {

  getRequest('xcx/user/info', defaultParams(), function(res) {
    success(res.detail)
  })
}

///通过扫描小程序码获取的scene id（由后台创建二维码时提供）获取其对应的scene对应json数据
function getSceneFromMiniCodeBySceneID(sceneId, success) {
  getRequest('xcx/get/scene', {
    "scene_id": sceneId
  }, function(res) {
    console.log("===========================扫描二维码进入")
    console.log(res)
    success(res)
  })
}



var imageNames = []
var imageUrls = []
//多张图片上传
function uploadimg(data) {
  console.log(data)
  if (data.path.length == 0) {
    return
  }
  var i = data.i ? data.i : 0,
    success = data.success ? data.success : 0,
    fail = data.fail ? data.fail : 0;
  let app = getApp()
  wx.uploadFile({
    url: 'https://wx.extend.xuemei99.com/xcx/api/upload',
    filePath: data.path[i],
    name: 'file',
    formData: {
      "imageIndex": i
    },
    header: {
      'content-type': 'multipart/form-data',
      'Authorization': app.globalData.token,
      'version': version
    },
    success: (resp) => {
      console.log(resp)
      console.log("shangchaun success")
      success++;
      if (resp.statusCode == 200) {
        let data = JSON.parse(resp.data)
        console.log(data)
        imageUrls.push(data.path)
        imageNames.push(data.name)
      }
      //这里可能有BUG，失败也会执行这里
    },
    fail: (res) => {
      fail++;
      console.log('fail:' + i + "fail:" + fail);
    },
    complete: () => {
      console.log(i);
      i++;
      if (i == data.path.length) { //当图片传完时，停止调用
        console.log('执行完毕');
        console.log('成功：' + success + " 失败：" + fail);
        let totalImages = JSON.parse(JSON.stringify(imageUrls)) //深拷贝图片数组已被传出去。
        let totalImageNames = JSON.parse(JSON.stringify(imageNames))
        imageNames = [] ///清空全局变量，避免造成对后续操作的干扰
        imageUrls = []

        data.finished({
          "images": totalImages,
          'imageNames': totalImageNames,
          "failNum": fail
        })
      } else { //若图片还没有传完，则继续调用函数
        data.i = i;
        data.success = success;
        data.fail = fail;
        uploadimg(data);
      }
    }
  })
}

function requestForMusicList(success) {
  getRequest("klk/music/list", defaultParams(), function(res) {
    success(res)
  })
}


function requestToGetNotifications(success) {
  getRequest("klk/check/message", defaultParams(), function(res) {
    let obj = res.detail
    getApp().globalData.newApplications = obj.activity
    getApp().globalData.newMessages = obj.message
    if (obj.activity > 0) {
      wx.showTabBarRedDot({
        index: 3,
      })
    }
    if (obj.message > 0) {
      wx.setTabBarBadge({
        index: 2,
        text: String(obj.message),
      })
    }
    success(res)
  })
}


function getVersionCode() {
  return version
}

/**
 * 已註冊
 * **/
function rerigtered(obj, logRes) {
  getApp().globalData.token = logRes.data.detail.token,
    getApp().globalData.openid = logRes.data.detail.openid
  getApp().globalData.owner = logRes.data.detail.owner
  // getApp().globalData.shop_id = logRes.data.detail.shopId
  getApp().globalData.phone = logRes.data.detail.phone
  console.log(obj)
  obj.success(logRes)
}

/**
 * 未注册
 * **/
function unregistered(obj, logRes) {
  getAuthorization(function success(res) {
    console.log(res)
    var userInfo = JSON.parse(res.rawData)
    updateUserinfo(logRes.data.detail.openid, res.iv, res.encryptedData, userInfo.nickName, userInfo.gender == true ? 0 : 1, userInfo.avatarUrl, function(useInfoRes) {
      getApp().globalData.token = useInfoRes.detail.token
      getApp().globalData.openid = useInfoRes.detail.openid
      getApp().globalData.owner = logRes.data.detail.owner
      //  getApp().globalData.shop_id = logRes.data.detail.shopId
      obj.success(useInfoRes)
    })
  }, function fail(res) {
    wx.showModal({
      title: '授权提示',
      content: '若需登录学妹店上店，店上店需要获取你的公开信息(昵称,头像等)',
      success(res) {
        if (res.cancel) {
          obj.fail(logRes)
        }
        if (res.confirm) {
          wx.openSetting({
            success(res) {
              wx.showToast({
                title: '授权成功',
              })
              wx.getUserInfo({
                success: res => {
                  var userInfo = JSON.parse(res.rawData)
                  updateUserinfo(logRes.data.detail.openid, res.iv, res.encryptedData, userInfo.nickName, userInfo.gender == true ? 0 : 1, userInfo.avatarUrl, function(useInfoRes) {
                    getApp().globalData.token = useInfoRes.detail.token
                    getApp().globalData.openid = useInfoRes.detail.openid
                    getApp().globalData.owner = logRes.data.detail.owner
                    //  getApp().globalData.shop_id = logRes.data.detail.shopId
                    obj.success(useInfoRes)
                  })

                }
              })
            }
          })
        }
      }
    })
  })
}

/**
 * 分享判断是否为店家
 * **/
function ownerShare(successFun){
  let isOwner = getApp().globalData.owner
  if(isOwner){
    getRequest('xcx/share/shop',{},function(res){
    successFun(res.detail)
    })
  }else{
    successFun(getApp().globalData.shop_id)
  }
}

module.exports = {
  postRequest: postRequest,
  getRequest: getRequest,
  defaultParams: defaultParams,
  shopParams: shopParams,
  login: login,
  getAuthorization: getAuthorization,
  ///从后台的获取用户注册信息
  getUserInformation: getUserInformation,
  ///更新用户信息
  updateUserinfo: updateUserinfo,
  //通过扫描小程序码获取的scene id（由后台创建二维码时提供）获取其对应的json数据(由使用者自己定义的scene数据结构)
  getSceneFromMiniCodeBySceneID: getSceneFromMiniCodeBySceneID,
  ///获取音乐列表
  requestForMusicList: requestForMusicList,
  ///上传图片
  uploadimg: uploadimg,
  ///获取版本号
  getVersionCode: getVersionCode,
  ///获取消息及活动通知
  requestToGetNotifications: requestToGetNotifications,
  ///走已注册逻辑
  rerigtered: rerigtered,
  ///走未注册逻辑
  unregistered: unregistered,
  ///分享判断是否为商家
  ownerShare: ownerShare
}